package com.platform.utils;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.platform.bean.SimilarImageResult;
import okhttp3.*;
import org.json.JSONException;
import org.json.JSONObject;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.List;

public class BaiduSimilarImageServerUtils {

    public static final String API_KEY = "SSGU5zeNRJgvJ1p1dA3oAOX4";
    public static final String SECRET_KEY = "OTR2Q2PCK9mfuboxFGXfhtfgdHn8te2h";

    static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();

    static String getAccessToken() throws IOException, JSONException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API_KEY
                + "&client_secret=" + SECRET_KEY);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token")
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        String accessToken = new JSONObject(response.body().string()).getString("access_token");
        System.out.println(accessToken);
        return accessToken;
//        MediaType mediaType = MediaType.parse("application/json");
//        RequestBody body = RequestBody.create(mediaType, "");
//        Request request = new Request.Builder()
//                .url("https://aip.baidubce.com/oauth/2.0/token?client_id="+API_KEY+
//                        "&client_secret=" + SECRET_KEY + "&grant_type=client_credentials")
//                .method("POST", body)
//                .addHeader("Content-Type", "application/json")
//                .addHeader("Accept", "application/json")
//                .build();
//        Response response = HTTP_CLIENT.newCall(request).execute();
//        return new JSONObject(response.body().string()).getString("access_token");
    }

    public static int addImage(Map<String, Object> params) throws IOException, JSONException {
        String requestBody = generateRequestBody(params);
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, requestBody);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rest/2.0/image-classify/v1/realtime_search/product/add?access_token=" + getAccessToken())
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        if(response.isSuccessful()) {
            String jsonString = response.body().string(); // 读取响应体为字符串
            Gson gson = new Gson();
            JsonObject jsonObject = gson.fromJson(jsonString, JsonObject.class); // 解析JSON字符串为JsonObject
            if (jsonObject.has("error_code")) { // 检查是否存在error_code字段
                int errorCode = jsonObject.get("error_code").getAsInt(); // 提取error_code字段的值
                System.out.println("Error Code: " + errorCode);
                return errorCode;
            }
            return 200;
        } else {
            return -1;
        }
    }

    public static int updateImage(Map<String, Object> params) throws IOException, JSONException {
        String requestBody = generateRequestBody(params);
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, requestBody);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rest/2.0/image-classify/v1/realtime_search/product/update?access_token=" + getAccessToken())
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        if(response.isSuccessful()) {
            String jsonString = response.body().string(); // 读取响应体为字符串
            Gson gson = new Gson();
            JsonObject jsonObject = gson.fromJson(jsonString, JsonObject.class); // 解析JSON字符串为JsonObject
            if (jsonObject.has("error_code")) { // 检查是否存在error_code字段
                int errorCode = jsonObject.get("error_code").getAsInt(); // 提取error_code字段的值
                System.out.println("Error Code: " + errorCode);
                return errorCode;
            }
            return 1;
        } else {
            return -1;
        }
    }

//    SimilarImageResponse
    public static Map<String, Object> searchSimilarImageBrief(Map<String, Object> params) throws IOException, JSONException {
//        params.put("image", params.get("image").toString().split(",")[1]);
        String requestBody = generateRequestBody(params);
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, requestBody);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rest/2.0/image-classify/v1/realtime_search/product/search?access_token=" + getAccessToken())
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        if(response.isSuccessful()) {
            Map<String, Object> similarImageResponse = new HashMap<>();
            List<SimilarImageResult> similarImageResultList = new ArrayList<>();
            String jsonString = response.body().string(); // 读取响应体为字符串
            Gson gson = new Gson();
            JsonParser parser = new JsonParser();
            JsonObject jsonObject = gson.fromJson(jsonString, JsonObject.class); // 解析JSON字符串为JsonObject
            if (jsonObject.has("error_code")) { // 检查是否存在error_code字段
                int errorCode = jsonObject.get("error_code").getAsInt(); // 提取error_code字段的值
                System.out.println("Error Code: " + errorCode);
            }
            int resultNum = jsonObject.get("result_num").getAsInt(); // uint32类型在Java中通常使用int表示
//            System.out.println(resultNum);
//            similarImageResponse.set(resultNum);
            JsonArray resultArray = jsonObject.get("result").getAsJsonArray(); // 结果数组
            // 遍历结果数组，提取每个结果中的参数
            for (int i = 0; i < resultArray.size(); i++) {
                SimilarImageResult similarImageResult = new SimilarImageResult();
                JsonObject resultObj = resultArray.get(i).getAsJsonObject();
                similarImageResult.setContSign(resultObj.get("cont_sign").getAsString());
                similarImageResult.setScore(resultObj.get("score").getAsFloat());
                similarImageResult.setBrief(resultObj.get("brief").getAsString());
                similarImageResultList.add(similarImageResult);
            }
            similarImageResponse.put("similarImageResultList", similarImageResultList);
            similarImageResponse.put("total", resultNum);
            PrintMessageUtils.traverseList(similarImageResultList);
            return similarImageResponse;
        } else {
            return null;
        }
    }

    public static int deleteImage(Map<String, Object> params) throws IOException, JSONException {
        String imageUrl = (params.get("imageUrl").toString());
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "url=" + imageUrl);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rest/2.0/image-classify/v1/realtime_search/product/delete?access_token=" + getAccessToken())
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        if(response.isSuccessful()) {
            return 1;
        } else {
            return -1;
        }
    }

    private static String generateRequestBody(Map<String, Object> params) throws UnsupportedEncodingException {
        StringBuilder sb = new StringBuilder();
        String classId1 = params.get("classId1").toString();
        //System.out.println(classId1);
        //String classId2 = params.get("classId2").toString();
        if (params.get("brief") != null) {
            String brief = params.get("brief").toString();
            sb.append("brief=").append(brief).append("&class_id1=").append(classId1);
            if(params.get("classId2") != null) {
                sb.append("&class_id2=").append(params.get("classId2").toString());
            }
        } else {
            sb.append("class_id1=").append(classId1);
            if(params.get("classId2") != null) {
                sb.append("&class_id2=").append(params.get("classId2").toString());
            }
        }
        System.out.println(sb.toString());
        if (params.get("image") != null) {
            sb.append("&image=").append(URLEncoder.encode(params.get("image").toString(), StandardCharsets.UTF_8.name()));
        } else if (params.get("url") != null) {
            sb.append("&url=").append(params.get("url").toString());
        }
        Integer pageSize = null;
        if (params.get("rn") != null) {
            pageSize = Integer.parseInt(params.get("rn").toString());
            sb.append("&rn=").append(pageSize);
        }
        if (params.get("pn") != null) {
            Integer pageNo = Integer.parseInt(params.get("pn").toString());
            if (pageSize != null && pageNo > 0) {
                pageNo = (pageNo - 1) * pageSize;
            }
            sb.append("&pn=").append(pageNo);
        }
        return sb.toString();
    }
}
